package wxy;

public class Week1_1_11_strToInt {

    public int strToInt(String str) {
        int boundary = Integer.MAX_VALUE / 10;
        int ans = 0;
        int i = 0;
        int sign = 1;
        while (i < str.length()) {
            if (str.charAt(i) != ' ') {
                break;
            }
            i++;
        }
        if (i == str.length()) {
            return 0;
        }
        if (str.charAt(i) == '-') {
            sign = -1;
            i++;
        } else if (str.charAt(i) == '+') {
            i++;
        }
        for (int j = i; j < str.length(); j++) {
            if (str.charAt(j) < '0' || str.charAt(j) > '9') {
                break;
            }
            int digit = str.charAt(j) - '0';
            if (ans < boundary || (ans == boundary && digit <= 7)) {
                ans = ans * 10 + digit;
            }else{
                return sign==1?Integer.MAX_VALUE:Integer.MIN_VALUE;
            }
        }
        return sign * ans;
    }
}

